<template>
<!-- 结算单据列表 -->
    <div class="e-form">
        <BillTop @cancel="printHandel"></BillTop>
        <div class="tabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- <el-tab-pane v-for="(item,index) in tabPaneList" :label="item.label" :name="item.name" :disabled="clickTabFlag" :key="index"></el-tab-pane> -->
                <el-tab-pane label="工程结算单据列表" name="project" :disabled="clickTabFlag" v-if="contractType==1"></el-tab-pane>
                <el-tab-pane label="工程终期结算单据列表" name="projectLast" :disabled="clickTabFlag" v-if="contractType==1"></el-tab-pane>
                <el-tab-pane label="其他结算单据列表" name="other" :disabled="clickTabFlag" v-if="contractType==2"></el-tab-pane>
                <el-tab-pane label="返还保证金结算单据列表" name="bond" :disabled="clickTabFlag" v-if="contractType==1"></el-tab-pane>
                <el-tab-pane label="材料加扣款结算单据列表" name="stuff" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <!-- 工程 -->
                    <div class="projectBox itemBox" id="project" v-if="contractType==1">
                        <div class="tabs-title">工程结算单据列表</div>
                        <div class="e-tree-table">
                        <el-table
                            ref="projectListTable"
                            key="tableRef"
                            border
                            style="width: 100%"
                            row-key="id"
                            :data="projectList"
                            class="table"
                            :max-height="$store.state.tableHeight"
                            v-sortTable="{ 'tableData': projectList, '_this': this, 'ref': 'projectListTable' }"
                        >
                        <el-table-column
                            prop="billNo"
                            label="结算编号"
                            min-width="200"
                            class-name="blue-column"
                            fixed
                        >
                            <template slot-scope="{ row }">
                                <span @click="projectEvent(row,1)">{{ row.billNo || '无'}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="settlementDate"
                            label="结算日期"
                            width="120"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="period"
                            label="期数"
                            width="100"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="contractName"
                            label="合同名称"
                            min-width="200"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="outsourcerName"
                            label="外包方"
                            min-width="200"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="orgName"
                            label="录入机构"
                            min-width="200"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="excludingDepositAmount"
                            label="本期结算金额（不含保证金）"
                            width="200"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="taxAmount"
                            label="税额"
                            width="120"
                        >
                        </el-table-column>
                        <el-table-column prop="totalAmount" width="200" label="本期结算金额（含税）">
                        </el-table-column>
                        <el-table-column prop="currentTotalAmount" width="200" label="截止本期末累计结算金额（含税）">
                        </el-table-column>
                        <el-table-column prop="state" width="100" label="状态">
                        <template slot-scope="{ row,$index }">
                            <ToolHistory v-if="row.state == 1" :key="$index" url="/projectsettle/flowEngin/getAuditHistory" :billId="row.billId" :billType="1099">
                                <span v-status="row.state">
                                   {{ getState(row.state) }}
                                </span>
                            </ToolHistory>
                            <span v-else v-status="row.state">
                                {{ getState(row.state) }}
                            </span>
                        </template>
                        </el-table-column>
                        <el-table-column prop="sendEasState" width="150" label="传输财务共享">
                        </el-table-column>
                    </el-table>
                    </div>
                    </div>
                    <!-- 终期 -->
                    <div class="projectLastBox itemBox" id="projectLast"
                    v-if="contractType==1">
                    <div class="tabs-title" >工程终期结算单据列表</div>
                        <div class="e-tree-table">
                        <el-table
                            ref="projectLastListTable"
                            key="tableRef"
                            border
                            style="width: 100%"
                            row-key="id"
                            :data="projectLastList"
                            class="table"
                            :max-height="$store.state.tableHeight"
                            v-sortTable="{ 'tableData': projectLastList, '_this': this, 'ref': 'projectLastListTable' }"
                        >
                        <el-table-column
                            prop="billNo"
                            label="结算编号"
                            min-width="200"
                            class-name="blue-column"
                            fixed
                        >
                            <template slot-scope="{ row }">
                                <span @click="projectEvent(row,2)">{{ row.billNo || '无'}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="settlementDate"
                            label="结算日期"
                            width="120"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="period"
                            label="期数"
                            width="100"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="contractName"
                            label="合同名称"
                            min-width="200"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="outsourcerName"
                            label="外包方"
                            min-width="200"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="orgName"
                            label="录入机构"
                            min-width="200"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="excludingDepositAmount"
                            label="本期结算金额（不含保证金）"
                            width="200"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="taxAmount"
                            label="税额"
                            width="120"
                        >
                        </el-table-column>
                        <el-table-column prop="totalAmount" width="200" label="本期结算金额（含税）">
                        </el-table-column>
                        <el-table-column prop="currentTotalAmount" width="200" label="截止本期末累计结算金额（含税）">
                        </el-table-column>
                        <el-table-column prop="state" width="100" label="状态">
                            <template slot-scope="{ row,$index }">
                                <ToolHistory v-if="row.state == 1" :key="$index" url="/projectsettle/flowEngin/getAuditHistory" :billId="row.billId" :billType="1098">
                                    <span v-status="row.state">
                                        {{ getState(row.state) }}
                                    </span>
                                </ToolHistory>
                                <span v-else v-status="row.state">
                                    {{ getState(row.state) }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="sendEasState" width="150" label="传输财务共享">
                        </el-table-column>
                    </el-table>
                    </div>
                    </div>
                    <!-- 其他 -->
                    <div class="otherBox itemBox" id="other" v-if="contractType==2">
                        <div class="tabs-title">其他结算单据列表</div>
                        <div class="e-tree-table">
                        <el-table
                            ref="otherListTable"
                            key="tableRef"
                            border
                            style="width: 100%"
                            row-key="id"
                            :data="otherList"
                            class="table"
                            :max-height="$store.state.tableHeight"
                            v-sortTable="{ 'tableData': otherList, '_this': this, 'ref': 'otherListTable' }"
                        >
                        <el-table-column
                            prop="billNo"
                            label="结算编号"
                            min-width="200"
                            class-name="blue-column"
                            fixed
                        >
                            <template slot-scope="{ row }">
                                <span @click="projectEvent(row,3)">{{ row.billNo || '无'}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="settlementDate"
                            label="结算日期"
                            width="120"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="period"
                            label="期数"
                            width="100"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="contractName"
                            label="合同名称"
                            min-width="200"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="outsourcerName"
                            label="外包方"
                            min-width="200"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="orgName"
                            label="录入机构"
                            min-width="200"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="excludingDepositAmount"
                            label="本期结算金额（不含保证金）"
                            width="200"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="taxAmount"
                            label="税额"
                            width="120"
                        >
                        </el-table-column>
                        <el-table-column prop="totalAmount" width="200" label="本期结算金额（含税）">
                        </el-table-column>
                        <el-table-column prop="currentTotalAmount" width="200" label="截止本期末累计结算金额（含税）">
                        </el-table-column>
                        <el-table-column prop="state" width="100" label="状态">
                            <template slot-scope="{ row,$index }">
                                <ToolHistory v-if="row.state == 1" :key="$index" url="/projectsettle/flowEngin/getAuditHistory" :billId="row.billId" :billType="1095">
                                    <span v-status="row.state">
                                        {{ getState(row.state) }}
                                    </span>
                                </ToolHistory>
                                <span v-else v-status="row.state">
                                    {{ getState(row.state) }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="sendEasState" width="150" label="传输财务共享">
                        </el-table-column>
                    </el-table>
                    </div>
                    </div>
                    <!-- 保证金 -->
                    <div class="bondBox itemBox" id="bond" v-if="contractType==1">
                        <div class="tabs-title">返还保证金结算单据列表</div>
                        <div class="e-tree-table">
                        <el-table
                            ref="bondListTable"
                            key="tableRef"
                            border
                            style="width: 100%"
                            row-key="id"
                            :data="bondList"
                            class="table"
                            :max-height="$store.state.tableHeight"
                            v-sortTable="{ 'tableData': bondList, '_this': this, 'ref': 'bondListTable' }"
                        >
                        <el-table-column
                            prop="billNo"
                            label="结算编号"
                            min-width="200"
                            class-name="blue-column"
                            fixed
                        >
                            <template slot-scope="{ row }">
                                <span @click="projectEvent(row,4)">{{ row.billNo || '无'}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="settlementDate"
                            label="结算日期"
                            width="120"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="period"
                            label="期数"
                            width="100"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="contractName"
                            label="合同名称"
                            min-width="200"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="outsourcerName"
                            label="外包方"
                            min-width="200"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="orgName"
                            label="录入机构"
                            min-width="200"
                        >
                        </el-table-column>

                        <el-table-column prop="amount" width="200" label="返还保证金合计(元)">
                        </el-table-column>

                        <el-table-column prop="state" width="100" label="状态">
                            <template slot-scope="{ row,$index }">
                                <ToolHistory v-if="row.state == 1" :key="$index" url="/projectsettle/flowEngin/getAuditHistory" :billId="row.billId" :billType="1096">
                                    <span v-status="row.state">
                                        {{ getState(row.state) }}
                                    </span>
                                </ToolHistory>
                                <span v-else v-status="row.state">
                                    {{ getState(row.state) }}
                                </span>
                            </template>
                        </el-table-column>

                        <el-table-column prop="sendEasState" width="150" label="传输财务共享">
                        </el-table-column>
                    </el-table>
                    </div>
                    </div>
                    <!-- 加扣款 -->
                    <div class="stuffBox itemBox" id="stuff">
                        <div class="tabs-title">材料加扣款结算单据列表</div>
                        <div class="e-tree-table">
                        <el-table
                            ref="stuffListTable"
                            key="tableRef"
                            border
                            style="width: 100%"
                            row-key="id"
                            :data="stuffList"
                            class="table"
                            :max-height="$store.state.tableHeight"
                            v-sortTable="{ 'tableData': stuffList, '_this': this, 'ref': 'stuffListTable' }"
                        >
                        <el-table-column
                            prop="billNo"
                            label="结算编号"
                            min-width="200"
                            class-name="blue-column"
                            fixed
                        >
                            <template slot-scope="{ row }">
                                <span @click="projectEvent(row,5)">{{ row.billNo || '无'}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="settlementDate"
                            label="结算日期"
                            width="120"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="period"
                            label="期数"
                            width="100"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="settlementType"
                            label="加扣款类型"
                            width="150"
                        >
                            <template slot-scope="{ row }">
                                {{ getSettlementType(row.settlementType) }}
                            </template>
                        </el-table-column>
                          <el-table-column
                        prop="contractName"
                        label="合同名称"
                        min-width="200"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="outsourcerName"
                        label="外包方"
                        min-width="200"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="orgName"
                        label="录入机构"
                        min-width="200"
                        show-overflow-tooltip
                    >
                    </el-table-column>
                    <el-table-column
                        prop="amount"
                        label="加扣款合计"
                        width="150"
                    >
                    </el-table-column>
                     <el-table-column prop="state" width="100" label="状态">
                        <template slot-scope="{ row,$index }">
                            <ToolHistory v-if="row.state == 1" :key="$index" url="/projectsettle/flowEngin/getAuditHistory" :billId="row.billId" :billType="1097">
                                <span v-status="row.state">
                                   {{ getPlusDeductionState(row) }}
                                </span>
                            </ToolHistory>
                            <span v-else v-status="row.state">
                                {{ getPlusDeductionState(row) }}
                            </span>
                        </template>
                    </el-table-column>
                    </el-table>
                    </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <el-button
                    type="primary"
                    class="btn-blue"
                    @click="printHandel"
                    size="small"
                    v-debounce
                    >关闭
            </el-button>
        </div>
    </div>
</template>

<script>
import { throttle } from '@/utils/common'
import { mapState } from 'vuex'
import '@/utils/jquery.scrollTo.min'
import { getLs } from '@/api/settlementManagement/gongchengjieshuan/guochengjieshuan'
import otherRequest from '@/api/settlementManagement/otherSettlement/otherSettlement.js'
import { getMainList } from '@/api/settlementManagement/gongchengjieshuan/baozhengjin.js'
import { getJkkLs, getJkkType, getCurrentState } from '@/api/settlementManagement/gongchengjieshuan/jiakoukuan'
export default {
    data () {
        return {
            tabsName: 'project',
            billId: this.$route.query.billid,
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false,
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            winEvent: {},
            projectList: [], // 工程
            projectLastList: [], //终期
            otherList: [], // 其他
            bondList: [], // 保证金
            stuffList: [], // 加扣款
            projectQuery: {
                'beginDate': '',
                'contractName': '',
                'endDate': '',
                'keyword': '',
                'limit': 20,
                'orgId': '',
                'outsourcerName': '',
                'page': 1,
                'sendEasStates': [],
                'states': [],
            }, //列表请求参数
            contractType: 1, //合同类型
            tabPaneList: [], // 列表展示数据
            plusDeductionList: [], //加扣款类型
            //流程参数
            projectState: {
                'billId': '',
                'billType': '',
                'freeNextUnitIndex': 0,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            //工程类所有结算类型
            billType: {
                1: '1099', // 过程
                2: '1098', // 终期
                3: '1095', // 其他
                4: '1096', // 保证金
                5: '1097', // 加扣款
            },
            //工程类对应页面路由(编辑)
            projectEditUrl: {
                1: 'guochengJieshuanEdit',
                2: 'guochengZqJieshuanEdit',
                3: 'otherSettlementEdit',
                4: 'baozhengjinEdit',
                5: 'guochengJkkJieshuanEdit'
            },
            //工程类对应页面路由(详情)
            projectDetailsUrl: {
                1: 'guochengJieshuanView',
                2: 'guochengZqJieshuanView',
                3: 'otherSettlementDetail',
                4: 'baozhengjinView',
                5: 'guochengJkkJieshuanView'
            },
        }
    },
    watch: {
    },
    created () {
        this.contractType = this.$route.query.contractType
        // this.setTabPane()
    },
    mounted () {
        this.getTableData()
        this.getLastConHeight()
        // 保存所有tabName
        const arr = ['project', 'projectLast', 'other', 'bond', 'stuff']
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth
        this.screenHeight = document.documentElement.clientHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    computed: {
        ...mapState({
            state: state => state.equip.equipData.state, //通用流程状态
        }),
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 85 - this.lastConHeight
        },
        getPlusDeductionState () {
            return row =>{
                //工程和其他加扣款类型
                const typeObj = {
                    0: '待审',
                    1: '审核中',
                    2: '已审核',
                    3: '待汇总',
                    4: '已汇总',
                    5: '已作废',
                    9: '共享审核中',
                    '-1': '已删除'
                }
                const state = row.state
                return typeObj[state]
            }
        },
    },
    methods: {
        getTableData () {
            Promise.all([
                this.getType(),
                this.getProjectList(),
                this.getProjectLastList(),
                this.getOtherList(),
                this.getBondList(),
                this.getStuffList()
            ])
        },
        //获取加扣款类型
        async getType () {
            const resData = await getJkkType({
                dicName: '工程加扣款',
                isEnable: true,
            })
            this.plusDeductionList = resData
        },
        //获取工程列表
        getProjectList () {
            const query = { ...this.projectQuery, settlementType: 1 }
            getLs(query).then(resData => {
                this.projectList = resData.list || []
            })
        },
        //获取终期列表
        getProjectLastList () {
            const query = { ...this.projectQuery, settlementType: 2 }
            getLs(query).then(resData => {
                this.projectLastList = resData.list || []
            })
        },
        //获取其他结算
        getOtherList () {
            otherRequest.getListOtherSettlementData(this.projectQuery)
                .then(res=>{
                    this.otherList = res.list || []
                })
        },
        //获取保证金
        getBondList () {
            getMainList(this.projectQuery).then(res=>{
                this.bondList = res.list ? res.list : []
            })
        },
        //获取加扣款
        getStuffList () {
            getJkkLs(this.projectQuery).then(res=>{
                this.stuffList = res.list ? res.list : []
            })
        },
        //设置列表展示数据
        setTabPane () {
            let list = []
            if(this.contractType == 1) {
                list = [
                    { label: '工程结算单据列表', name: 'project' },
                    { label: '工程终期结算单据列表', name: 'projectLast' },
                    { label: '返还保证金结算单据列表', name: 'bond' },
                    { label: '材料加扣款结算单据列表', name: 'stuff' },
                ]
            }else {
                list = [
                    { label: '其他结算单据列表', name: 'other' },
                    { label: '材料加扣款结算单据列表', name: 'stuff' },
                ]
            }
            this.tabPaneList = list
        },

        //工程过程结算列表点击事件
        projectEvent (row, billType) {
            const billId = row.billId
            this.projectState.billId = billId
            this.projectState.billType = this.billType[billType]
            const state = row.state
            if(state == -1 || state == 2 || state == 5 ) {
                const path = this.projectDetailsUrl[billType]
                this.$router.push({
                    //此处需要拼接一个/
                    path: `/${path}`,
                    query: { billid: billId },
                })
            }else {
                getCurrentState(this.projectState).then(res => {
                    let name = this.projectDetailsUrl[billType]
                    if(res.canModify) {
                        name = this.projectEditUrl[billType]
                    }
                    //过程、保证金、加扣款
                    if([1, 4, 5].includes(billType)) {
                        this.$router.push({
                            name,
                            query: { billid: billId },
                            params: { auditState: res }
                        })
                    }
                    //其他、终期
                    else {
                        this.$router.push({
                            path: name,
                            query: { billid: billId }
                        })
                    }

                })
            }
        },

        //获取流程状态
        getState (state) {
            const findObj = this.state.find(item => item.value === Number(state))
            return findObj ? findObj.label : ''
        },
        //加扣款状态
        getSettlementType (type) {
            const findObj = this.plusDeductionList.find(item => Number(item.kvValue) === type)
            return findObj ? findObj.kvKey : ''
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                const lastCon = document.getElementById('auditHistoryCon')
                if (lastCon) {
                    const lastConHeight = lastCon.offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //返回
        printHandel () {
            this.$router.replace({
                path: '/projectSettlementAccountContractSettlementDetails',
                query: {
                    contractType: this.contractType
                }
            })
        },
    }
}
</script>

<style lang="scss" scoped>
.itemBox {
    margin-top: 20px;
}
</style>
